/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import tableApi from '@/api/common/tableApi'
export const RCListMixin = {
  data() {
    return {
      tableData: null,
      loading: true,
      queryParam: {
        pageNo: 1,
        pageSize: 10
      },
      currentPage: 1,
      pageTotal: 1,
      selectedIds: [],
      selectedDataAll: []
    }
  },
  created() {
    console.log(' -- mixin created -- ')
    this.getTableData()
    // 初始化字典配置 在自己页面定义
  },
  methods: {
    // 获取分页数据
    getTableData(arg) {
      this.loading = true
      if (this.url.list == null) {
        this.$message.error('请设置url.list!')
        return
      }
      if (arg === 1) {
        this.queryParam.pageNo = 1
      }
      tableApi.list(this.url.list, this.queryParam).then(
        (res) => {
          this.tableData = res.result.records // 表格数据
          this.currentPage = res.result.current // 当前页
          this.pageTotal = res.result.total // 总页数
          // 翻页记忆
          if (this.selectedDataAll[this.currentPage - 1] != undefined && this.selectedDataAll[this.currentPage - 1].length > 0) {
            this.$nextTick(() => {
              this.selectedDataAll[this.currentPage - 1].forEach(row => {
                console.log(row)
                this.$refs.table.toggleRowSelection(this.tableData.find(item => {
                  return row.id == item.id // 注意这里寻找的字段要唯一
                }), true)
              })
            })
          }
          this.loading = false
          // console.log(res.result.records);
        },
        (err) => {
          console.log(err)
          this.loading = false
        }
      )
    },
    // 分页改变
    handleCurrentChange(currentPage) {
      this.queryParam.pageNo = currentPage
      this.getTableData()
    },
    // 多选id
    handleSelectionChange(val) {},
    // 单选行
    handleSelect(selection) {
      this.selectedDataAll[this.currentPage - 1] = selection
      this.changeSelectedIds()
    },
    // 全选行
    handleSelectAll(selection) {
      this.selectedDataAll[this.currentPage - 1] = selection
      this.changeSelectedIds()
    },
    changeSelectedIds() {
      this.selectedIds = []
      this.selectedDataAll.forEach((table) => {
        table.forEach((row) => {
          this.selectedIds.push(row.id)
        })
      })
    },
    // 增删改刷新数据
    handleOK() {
      this.selectedIds = []
      this.selectedDataAll = []
      this.getTableData()
    },
    // 添加
    handleAdd() {
      console.log('handleAdd')
      this.$refs.modalForm.add()
      this.$refs.modalForm.visible = true
      this.$refs.modalForm.title = '新增'
    },
    // 编辑
    handleEdit(index, row) {
      console.log('handleEdit')
      // console.log(this.$refs.modalForm);
      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.visible = true
      this.$refs.modalForm.title = '编辑'
    },
    // 删除
    handleDelete(id) {
      console.log('handleDelete')
      console.log(id)
      if (this.url.delete == null) {
        this.$message.error('请设置url.delete!')
        return
      } else {
        tableApi.delete(this.url.delete, {
          id: id
        }).then(
          (res) => {
            console.log(res)
            this.$message({
              type: 'success',
              message: res.message
            })
            this.loading = false
            this.handleOK()
          },
          (err) => {
            console.log(err)
            this.$message({
              type: 'error',
              message: err.message
            })
            this.loading = false
            this.getTableData()
          }
        )
      }
    },
    // 批量删除
    handleDeleteBatch() {
      console.log('handleDeleteBatch')
      this.$confirm(`确认批量删除选择的${this.selectedIds.length}条数据吗?`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.url.deleteBatch == null) {
          this.$message.error('请设置url.deleteBatch!')
          return
        } else {
          tableApi.delete(this.url.deleteBatch, {
            ids: this.selectedIds.join(',')
          }).then(
            (res) => {
              console.log(res)
              this.$message({
                type: 'success',
                message: res.message
              })
              this.loading = false
              this.handleOK()
            },
            (err) => {
              console.log(err)
              this.$message({
                type: 'error',
                message: err.message
              })
              this.loading = false
            }
          )
        }
      }).catch(() => {})
    },
    // 查询
    searchQuery() {
      this.getTableData(1)
    },
    // 重置
    reset() {
      this.queryParam = {}
      this.queryParam.pageNo = 1
      this.queryParam.pageSize = 10
      this.selectedIds = []
      this.selectedDataAll = []
      this.getTableData()
    },
    // 导入Excel
    handleImportExcel(res) {
      console.log(res)
      if (res.code === 20002) {
        this.$message({
          type: 'warning',
          message: res.message
        })
      }
      if (res.code === 20000) {
        this.$message({
          type: 'success',
          message: res.message
        })
      }
      this.$refs.upload.clearFiles() // 上传成功之后清除历史记录
      this.loading = false
      this.reset()
    },
    // 导出Excel
    handleExportExcel() {
      tableApi.exportExcel(this.url.exportExcelUrl, {
        ids: this.selectedIds.join(','),
        ...this.queryParam
      }).then((res) => {
        if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE10对象
          window.navigator.msSaveBlob(new Blob([res], {
            type: 'application/vnd.ms-excel'
          }), this.excelName + '.xls')
        } else { // 普通对象
          const url = window.URL.createObjectURL(new Blob([res], {
            type: 'application/vnd.ms-excel'
          }))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', this.excelName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      }).catch(_ => {
        this.$message({
          type: 'error',
          message: '导出失败!'
        })
        this.loading = false
      })
    }
  }
}
